import { useIntersectionObserver } from '@vueuse/core';
import { ref, onUnmounted, computed } from 'vue';

// 核心单词解释：
// useIntersectionObserver  检测元素是否进入可视区域
// target                   目标元素需要配合ref模板使用
// isIntersecting           是否进入可是区域
// stop                     用于停止检测的函数
export const useObserver = (fn?: () => void) => {
  const target = ref(null);
  // 官网基本案例，供同学练习复制
  const { stop } = useIntersectionObserver(target, ([{ isIntersecting }]) => {
    // 写业务代码
    console.log('检测可是区域', isIntersecting);
    if (isIntersecting) {
      console.log('发送请求');
      fn && fn();
      // 停止检测
      stop();
    }
  });
  return { target };
};

import dayjs from 'dayjs';
export const useCounter = () => {
  const count = ref(0);
  let timer = 0;
  const start = (time = 60) => {
    if (count.value) return;
    if (time < 0) return;
    count.value = time;
    timer = setInterval(() => {
      count.value--;
      if (count.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  };
  //格式化日期
  const countTime = computed(() => {
    return dayjs.unix(count.value).format('mm分ss');
  });
  onUnmounted(() => clearInterval(timer));
  return { start, count, countTime };
};
